﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Atmk.WaterMeter.MIS.Commons.Interfaces.Repository;
using Atmk.WaterMeter.MIS.Datas;
using Atmk.WaterMeter.MIS.Entities.Enums;
using Atmk.WaterMeter.MIS.Entities.Models;

namespace Atmk.WaterMeter.MIS.Services.DataAccess
{
   public class StatisticHistoryRepository : IStatisticHistoryRepository
    {
        /// <summary>
        /// 添加指定统计类型的统计数据
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="statisticType"></param>
        /// <param name="data"></param>
        /// <returns></returns>
        public int Add(string projectId, StatisticType statisticType, string data)
        {
            var statisticHistory = new StatisticHistories
            {
                ProjectId = projectId,
                StatisticType = (int)statisticType,
                Memo = data
            };
            using (var c = ContextBuilder.Build())
            {
                c.StatisticHistories.Add(statisticHistory);
                return c.SaveChanges();
            }
        }

        /// <summary>
        /// 根据参数，按时间获取最新的统计记录的数据
        /// </summary>
        /// <param name="projectId"></param>
        /// <param name="statisticType"></param>
        /// <returns></returns>
        public string GetNewStatisticData(string projectId, StatisticType statisticType)
        {
            using (var c = ContextBuilder.Build())
            {
                //var list = c.StatisticHistories.Where(s => s.ProjectId == projectId).ToList();
                var result = c.StatisticHistories
                    .Where(s => s.ProjectId == projectId && s.StatisticType == (int)statisticType)
                    .OrderByDescending(s => s.CreateTime).ToList();
                return result.Count > 0 ? result.First().Memo : "";
            }
        }
    }
}